package com.bigdata.collector.dao;

import org.apache.log4j.Logger;

import com.bigdata.collector.model.Labels;
import com.bigdata.collector.util.StringUtil;

public class LabelsDAO extends BaseDAO<Labels> {

	private static Logger logger = Logger.getLogger(LabelsDAO.class);

	public int add(final Labels entity) throws Exception {
		int id = save(entity);
		return id;
	}

	public Labels findByID(int id) {
		Labels tags = null;
		try {
			tags = super.find(id, "id").get(0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return tags;
	}

	public Labels findByNormal(String normal) {
		Labels tags = null;
		try {
			if (super.find(normal, "tag_normal").size() > 0)
				tags = super.find(normal, "tag_normal").get(0);
		} catch (Exception e) {
			logger.error(e);
		}
		return tags;
	}

	public void update(final Labels entity) {
		try {
			super.update(entity);
		} catch (Exception e) {
			logger.error(e);
		}
	}

	public int singleSave(String t, String category) {
		if (!StringUtil.tagValidate(t)) {
			logger.info("not validate tag:" + t);
		} else {
			try {
				String tag_normal = StringUtil.tag2Normal(t);
				Labels tags = findByNormal(tag_normal);
				if (tags == null) {
					tags = new Labels();
					tags.setTag_normal(tag_normal);
					tags.setTag_show(StringUtil.tag2Show(t));
					tags.setCategory(category);
					add(tags);
					return 1;
				} else {
					logger.info("already in db tag:" + t);
					return 2;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return 0;
	}
}
